package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;


@RestController
@RequestMapping("/order")
public class OrderController_Mobile {

    @Reference
    private OrderService orderService;

    //注入JedisPool
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String, Object> map) {
        //校验验证码是否正确
        //获取手机号 通过手机号+验证码的指令 为键 获取值
        String telephone = (String) map.get("telephone");
        //提交表单的验证码
        String validateCode = (String) map.get("validateCode");
        //redis中存储的验证码
        String redisValidateCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (validateCode != null && redisValidateCode != null && validateCode.equals(redisValidateCode)) {
            //设置预约类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null;
            //调用业务层，保存预约信息，预约成功后给，用户发送短信
            try {
                result = orderService.add(map);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.ORDER_FALL);
            }
            //给用户发送预约成功信息
            if (result.isFlag()) {
                System.out.println("预约成功短信已发送!");
                //SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, (String) map.get("orderDate"));
            }
            return result;
        } else {//验证码校验失败
            //校验失败，返回结果到页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }

    @RequestMapping("/findById")
    public Result findById(String id){
        try {
            Map memberInfo = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, memberInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
